#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MINISQL_IMPLEMENTATION
#include "minisql.hol.h"

// 从CSV文件导入数据到表
int import_csv(MiniSQL* db, const char* table_name, const char* csv_file) {
    FILE* f = fopen(csv_file, "r");
    if (!f) {
        printf("无法打开CSV文件: %s\n", csv_file);
        return 1;
    }

    char* line = NULL;
    size_t len = 0;
    ssize_t read;
    int row_count = 0;

    // 读取表头（假设第一行是列名，这里跳过，因为表结构已存在）
    if ((read = getline(&line, &len, f)) != -1) {
        // 处理数据行
        while ((read = getline(&line, &len, f)) != -1) {
            // 移除换行符
            if (line[read-1] == '\n') line[read-1] = '\0';
            
            // 构建INSERT语句
            char sql[1024] = "INSERT INTO ";
            strcat(sql, table_name);
            strcat(sql, " VALUES (");
            
            char* token = strtok(line, ",");
            while (token) {
                // 判断是数字还是字符串
                int is_number = 1;
                for (int i = 0; token[i]; i++) {
                    if (!isdigit(token[i]) && token[i] != '-') {
                        is_number = 0;
                        break;
                    }
                }
                
                if (is_number) {
                    strcat(sql, token);
                } else {
                    strcat(sql, "'");
                    strcat(sql, token);
                    strcat(sql, "'");
                }
                
                token = strtok(NULL, ",");
                if (token) strcat(sql, ",");
            }
            strcat(sql, ")");
            
            // 执行SQL
            ResultSet* result = NULL;
            if (minisql_exec(db, sql, &result) != MINISQL_OK) {
                printf("导入失败: %s (SQL: %s)\n", minisql_errmsg(db), sql);
                break;
            }
            if (result) minisql_free_result(result);
            row_count++;
        }
    }

    printf("成功导入 %d 行数据\n", row_count);
    free(line);
    fclose(f);
    return 0;
}

// 将表导出为CSV文件
int export_csv(MiniSQL* db, const char* table_name, const char* csv_file) {
    FILE* f = fopen(csv_file, "w");
    if (!f) {
        printf("无法创建CSV文件: %s\n", csv_file);
        return 1;
    }

    // 查询所有数据
    char sql[1024];
    snprintf(sql, sizeof(sql), "SELECT * FROM %s", table_name);
    
    ResultSet* result = NULL;
    if (minisql_exec(db, sql, &result) != MINISQL_OK) {
        printf("查询失败: %s\n", minisql_errmsg(db));
        fclose(f);
        return 1;
    }

    if (!result || result->row_count == 0) {
        printf("表中没有数据\n");
        fclose(f);
        return 1;
    }

    // 写入表头
    for (int i = 0; i < result->column_count; i++) {
        fprintf(f, "%s", result->columns[i]);
        if (i < result->column_count - 1) fprintf(f, ",");
    }
    fprintf(f, "\n");

    // 写入数据行
    for (int r = 0; r < result->row_count; r++) {
        Row* row = result->rows[r];
        for (int c = 0; c < result->column_count; c++) {
            int col_idx = column_index(result->table, result->columns[c]);
            if (col_idx == -1) continue;
            
            Value* val = &row->values[col_idx];
            switch (val->type) {
                case MINISQL_TYPE_INT:
                    fprintf(f, "%lld", (long long)val->as.i);
                    break;
                case MINISQL_TYPE_TEXT:
                    fprintf(f, "%s", val->as.s);
                    break;
                default:
                    fprintf(f, "NULL");
                    break;
            }
            if (c < result->column_count - 1) fprintf(f, ",");
        }
        fprintf(f, "\n");
    }

    printf("成功导出 %d 行数据到 %s\n", result->row_count, csv_file);
    minisql_free_result(result);
    fclose(f);
    return 0;
}

int main(int argc, char* argv[]) {
    if (argc != 5) {
        printf("用法:\n");
        printf("  导入: %s import <数据库名> <表名> <CSV文件>\n", argv[0]);
        printf("  导出: %s export <数据库名> <表名> <CSV文件>\n", argv[0]);
        return 1;
    }

    MiniSQL* db = minisql_open(argv[2]);
    if (!db) {
        printf("无法打开数据库: %s\n", argv[2]);
        return 1;
    }

    if (strcmp(argv[1], "import") == 0) {
        import_csv(db, argv[3], argv[4]);
    } else if (strcmp(argv[1], "export") == 0) {
        export_csv(db, argv[3], argv[4]);
    } else {
        printf("未知操作: %s\n", argv[1]);
    }

    minisql_close(db);
    return 0;
}